import { Component, OnInit, ViewChild } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { STColumn, STComponent, STColumnButton } from '@delon/abc';
import { SFSchema, SFComponent } from '@delon/form';
import { GridComponent, HttpService, SupDic } from 'lbf';
import { NzMessageService, NzButtonComponent, NzDropdownMenuComponent, NzContextMenuService } from 'ng-zorro-antd';
import { truncate } from 'fs';

@Component({
  selector: 'app-xtgn-gwgl',
  templateUrl: './gwgl.component.html',
  styleUrls: ['./gwgl.less']
})
export class XtgnGwglComponent implements OnInit {
  searchValue = ''
  searchSxValue = ''
  nodes: any = [];
  cdnodes: any = [];
  sxnodes: any = [];
  treeData: any; // 当前所选节点
  yjData: any; // 右击所选节点
  fzData: any;// 复制所选节点
  cdtreeData = [];
  sxtreeData = [];
  dgb040: any;
  style = { height: (window.outerHeight - 330) + 'px', overflow: 'auto' }

  // 功能、业务复制
  fzFlag = 0;
  gndisabled = true;
  ywdisabled = true;
  bothdisabled = true;
  copydisabled = false;

  isSaveDisabled = true;

  isAddDisabled = true;
  isDelDisabled = true;
  isXtDisabled = true;
  isYwDisabled = true;
  isAddUserDisabled = true;
  formData = {};
  isVisible = false;
  isCdVisible = false;
  isYwVisible = false;
  chVisible = false;
  modalTitle = '创建下属岗位';
  modalCdTitle = '设置系统权限';
  modalYwTitle = '设置业务权限';
  params = { sname: 'gwgl_yhcx', queryparas: {} }
  isYhVisible = false;

  editSchema: SFSchema = {
    properties: {
      ROLEID: {
        type: 'string',
        title: '岗位编码',
        readOnly: true,

      },
      DGB021: {
        type: 'string',
        title: '机构名称',
        readOnly: true


      },

      DGB040: {
        type: 'string',
        title: '所属科室',
        readOnly: true,
        ui: {
          widget: 'select',
        },
        enum: this.supdic.getSFDic("DGB040")
      },
      RNAME: {
        type: 'string',
        title: '岗位名称',
      },
    },
    ui: {
      spanLabelFixed: 100,
      grid: {
        span: 12
      }
    },
    required: ["RNAME"]
  }

  newYhSchema: SFSchema = {
    properties: {
      UNAME: {
        type: 'string',
        title: '登录名'
      },
      NAME: {
        type: 'string',
        title: '用户名'
      },
      PHONE: {
        type: 'string',
        title: '手机号码'
      },
      FLAG: {
        type: 'string',
        title: '派件状态',
        ui: {
          widget: 'select',
        },
        enum: this.supdic.getSFDic("AAE100")
      },
      ROLEID: {
        type: 'string',
        title: '岗位',
        ui: {
          hidden: true
        }
      }
    },
    required: ['UNAME', 'NAME', 'PHONE', 'FLAG'],
    ui: {
      spanLabelFixed: 80,
      grid: {
        gutter: 20,
        span: 24
      }
    }
  }

  addSchema: SFSchema = {
    properties: {
      DGB021: {
        type: 'string',
        title: '所属机构',
        readOnly: true
        // ui: {
        //   widget: 'select'
        // },
        // enum: this.supdic.getSFDic("DGB040")
      },
      RNAME: {
        type: 'string',
        title: '岗位名称'
      },
    },
    required: ["DGB021", "RNAME"],
    ui: {
      spanLabelFixed: 80,
      grid: {
        gutter: 20,
        span: 24
      }
    }
  }

  changeSchema: SFSchema = {
    properties: {},
  };

  yhColumns: STColumn[] = [

    { title: '登录名', index: 'UNAME' },
    { title: '用户名', index: 'NAME' },
    { title: '手机号码', index: 'PHONE' },
    { title: '状态', index: 'STATUS', dic: 'AAE100' },
    { title: '派件状态', index: 'FLAG', dic: 'AAE100' },
    {
      title: '操作区',
      buttons: [
        {
          text: '更改',
          click: (record: any) => this.updateService(record),
        },
        {
          text: '删除',
          click: (record: any) => this.delete(record),
          pop: true,
          popTitle: '确定删除该任务？',
        },
      ],
    },
  ]

  @ViewChild('sf', { static: false }) sf: SFComponent;
  @ViewChild('addSf', { static: false }) addSf: SFComponent;
  @ViewChild('st', { static: false }) st: GridComponent;
  @ViewChild('yhsf', { static: false }) yhsf: SFComponent;
  @ViewChild('fzsf', { static: false }) fzsf: SFComponent;
  @ViewChild('changePop', { static: false }) changePop: SFComponent;

  constructor(private lbservice: HttpService,
    private msgSrv: NzMessageService,
    private supdic: SupDic, private nzContextMenuService: NzContextMenuService
  ) { }



  ngOnInit() {
    this.initGwTree();
  }

  // 初始化岗位树
  initGwTree() {
    this.lbservice.lbservice('gwgl_gwlist', {}).then(res => {

      this.nodes = res.message.list;
      console.log("岗位树");
      console.log(this.nodes)
    });
  }

  initCdTree() {
    this.lbservice.lbservice('gwgl_cdlist', { ROLEID: this.treeData.roleid }).then(res => {
      console.log(res.message.list);
      this.cdnodes = res.message.list;
    });
  }

  addYh() {
    this.isYhVisible = true;
  }

  handleYhOk() {
    this.lbservice.lbservice("yhgl_yhxz", { para: this.yhsf.value }).then(result => {
      if (result.code < 1) {
        this.msgSrv.error(result.errmsg);
      } else {
        this.msgSrv.success("用户新增成功");
        this.st.reload({ ROLEID: this.params.queryparas });
        this.isYhVisible = false;
      }
    })

  }

  initSxTree() {
    this.lbservice.lbservice('gwgl_sxlist', { ROLEID: this.treeData.roleid }).then(res => {
      console.log(res.message.list);
      this.sxnodes = res.message.list;

    });
  }
  nzEvent(event) {
    this.cdtreeData = []
    this.sxtreeData = []
    this.isSaveDisabled = true;
    this.isDelDisabled = true;
    this.isAddDisabled = false;
    this.isXtDisabled = true;
    this.isYwDisabled = true;
    this.sf.refreshSchema();
    this.treeData = event.node.origin;
    console.log(this.treeData)



    if (this.treeData.hasOwnProperty("dgb021")) {

      this.sf.setValue('/DGB021', this.treeData.dgb021);



    }

    if (this.treeData.hasOwnProperty("biaozhi")) {
      this.isAddDisabled = false;

    }


    if (this.treeData.hasOwnProperty("roleid")) {
      // 编辑框表单赋值
      this.yhsf.setValue('/ROLEID', this.treeData.roleid);
      if (this.treeData.roleid !== '0' && this.treeData.roleid !== '1') {
        this.sf.setValue('/DGB040', event.node.parentNode.origin.dgb040);
        this.sf.setValue('/RNAME', this.treeData.rname);
        this.sf.setValue('/ROLEID', this.treeData.roleid);

        this.isSaveDisabled = true;
        this.isXtDisabled = false;
        this.isYwDisabled = false;
        this.isDelDisabled = false;

      }

      if (this.treeData.roleid === '1') {
        this.isXtDisabled = false;
        this.isYwDisabled = false;
      }

      this.params.queryparas = this.treeData.roleid;
      console.log(this.params.queryparas)
      this.st.reload({ ROLEID: this.params.queryparas });
      this.isAddUserDisabled = false;

    } else {

      this.st.reload({});
    }

    if (this.treeData.hasOwnProperty("dgb040")) {
      this.isAddDisabled = false;
      this.dgb040 = event.node.origin.dgb040;
    }
  }

  nzCdEvent(event) {
    this.cdtreeData = event.keys;
  }

  nzSxEvent(event) {
    console.log(event)
    // const testArr = [1,2,3,4,5];
    //    const start = testArr.indexOf(2);
    //   testArr.splice(start,1);
    //   console.log(testArr)
    if (event.eventName === 'check') {
      const node = event.node.origin;
      const elem = { DAD017: node.dad017, DAD090: node.dad090, DAE001: node.dae001 }
      if (node.checked === true) {
        this.sxtreeData.push(elem);
      }
      if (node.checked === false) {
        this.sxtreeData = this.deleteItem(this.sxtreeData, elem);
        console.log(this.sxtreeData);
      }
    }
  }

  deleteItem(array, item) {
    console.log(array);
    console.log(item);
    const index =
      array.findIndex(text => text.DAD017 === item.DAD017 && text.DAD090 === item.DAD090 && text.DAE001 === item.DAE001);
    console.log(index);
    array.splice(index, 1);
    return array;
  }

  formChanged(event) {
    this.isSaveDisabled = false;

  }

  add(value: any) {

    if (value.DGB021 == null) {
      this.isVisible = false;
      return this.msgSrv.error("已经是最底层了!");

    } else {
      this.isVisible = true;
      console.log(value)
      this.addSf.setValue('/DGB021', value.DGB021);

    }
  }

  addXt() {
    this.initCdTree();
    this.lbservice.lbservice('gwgl_initCdData', { ROLEID: this.treeData.roleid }).then(res => {
      res.message.list.forEach((item, index, arr) => {
        const fid = item.fid;
        this.cdtreeData.push(fid);
      })
    })
    console.log(this.cdtreeData)
    this.isCdVisible = true
  }

  addYw() {
    this.initSxTree();
    this.lbservice.lbservice('gwgl_initSxData', { ROLEID: this.treeData.roleid }).then(res => {
      this.sxtreeData = res.message.list;
    })
    this.isYwVisible = true;
  }



  save() {
    if (!this.sf.valid) {
      this.msgSrv.error('必填项不能为空！');
      return;
    }
    this.lbservice.lbservice('gwgl_gwxg', { para: this.sf.value }).then(resdata => {
      console.log(this.sf.value);
      if (resdata.code < 1) {
        this.msgSrv.error(resdata.errmsg);
      }
      else {
        this.msgSrv.success('修改成功');
        this.isSaveDisabled = true;
        this.initGwTree();
      }

    })

  }

  del() {
    this.lbservice.lbservice("gwgl_gwsc", { ROLEID: this.sf.value.ROLEID }).then(result => {
      if (result.code < 1) {
        this.msgSrv.error(result.errmsg);

      } else {
        this.msgSrv.success("删除成功");
        this.initGwTree();
        this.sf.reset();
      }

    })
  }

  handleCancel() {
    this.isVisible = false;
    this.isCdVisible = false;
    this.isYwVisible = false;
    this.formData = {};
  }

  handleOkCd() {
    this.lbservice.lbservice('gwgl_xtqx', { FIDS: this.cdtreeData, ROLEID: this.treeData.roleid }).then(result => {
      if (result.code < 1) {
        this.msgSrv.error(result.errmsg);
      } else {
        this.msgSrv.success("设置系统权限成功");
      }
    })
    this.isCdVisible = false;
  }

  handleOkYw() {
    console.log(this.sxtreeData)
    this.lbservice.lbservice('gwgl_ywqx', { SXLIST: this.sxtreeData, ROLEID: this.treeData.roleid }).then(result => {
      if (result.code < 1) {
        this.msgSrv.error(result.errmsg);
      } else {
        this.msgSrv.success("设置业务权限成功");
      }
    })
    this.isYwVisible = false;
  }


  saveAdd(data) {
    this.lbservice.lbservice("gwgl_gwxz", { para: data }).then(result => {
      if (result.code < 1) {
        this.msgSrv.error(result.errmsg);
      } else {
        this.addSf.reset();
        this.msgSrv.success("新增成功");
        this.initGwTree();
      }
      this.isVisible = false;
    })
  }

  confirm() {
    this.del();
  }

  cancel() {

  }

  _onReuseInit() {
    this.initGwTree();
  }

  /*----------------- 复制操作  ------------------*/
  contextMenu($event: MouseEvent, menu: NzDropdownMenuComponent, node): void {
    console.log(node)
    this.yjData = node.origin;
    if (this.treeData.key === this.yjData.key) {
      this.nzContextMenuService.create($event, menu);
    }

  }

  cdfz() {
    this.fzFlag = 1;
    // 右击角色和粘贴角色一致 允许粘贴
    // 粘贴角色和复制角色一致
    if (this.treeData.key === this.fzData.key) {
      this.msgSrv.error('功能权限已存在')
    } else {
      this.lbservice.lbservice('gwgl_qxfz', {
        FZFLAG: this.fzFlag,
        ROLEID: this.fzData.key, TROLEID: this.treeData.key
      }).then(res => {
        if (res.code > 0) {
          this.msgSrv.info('功能权限粘贴成功')
        }
      })
    }

  }

  ywfz() {
    this.fzFlag = 2;
    if (this.treeData.key === this.fzData.key) {
      this.msgSrv.error('业务权限已存在')
    } else {
      this.lbservice.lbservice('gwgl_qxfz', {
        FZFLAG: this.fzFlag,
        ROLEID: this.fzData.key, TROLEID: this.treeData.key
      }).then(res => {
        if (res.code > 0) {
          this.msgSrv.info('业务权限粘贴成功')
        }
      })
    }
  }

  bothfz() {
    this.fzFlag = 3;
    if (this.treeData.key === this.fzData.key) {
      this.msgSrv.error('功能、业务权限已存在')
    } else {
      this.lbservice.lbservice('gwgl_qxfz', {
        FZFLAG: this.fzFlag,
        ROLEID: this.fzData.key, TROLEID: this.treeData.key
      }).then(res => {
        if (res.code > 0) {
          this.msgSrv.info('功能、业务权限粘贴成功')
        }
      })
    }
  }

  onCancel() {
    this.isYhVisible = false;
  }

  copy() {
    // 右击角色和点击角色一致才允许复制
    this.gndisabled = false;
    this.ywdisabled = false;
    this.bothdisabled = false;
    this.fzData = this.yjData;
    this.msgSrv.info('复制成功');
  }

  delete(rec: any) {
    this.lbservice
      .lbservice('FR_userdelete', { para: { USERID: rec.USERID } })
      .then(resdata => {
        if (resdata.code > 0) {
          this.msgSrv.success('删除成功');
        } else {
          this.msgSrv.error(resdata.errmsg);
        }
        this.st.reload();
      });
  }
  updateService(rec: any) {
    this.changeSchema = {
      properties: {
        USERID: {
          type: 'string',
          title: '用户ID',
          default: rec.USERID,
          ui: { hidden: true, }
        },
        UNAME: {
          type: 'string',
          title: '登录名',
          readOnly: true,
          default: rec.UNAME,
        },
        NAME: {
          type: 'string',
          title: '用户名',
          readOnly: true,
          default: rec.NAME,
        },
        PHONE: {
          type: 'string',
          title: '手机号码',
          default: rec.PHONE,
        },
        STATUS: {
          type: 'string',
          title: '状态',
          default: rec.STATUS,
          enum: this.supdic.getSFDic('AAE100'),
          ui: {
            widget: 'select',
            allowClear: true,
            grid: { span: 6 }
          }
        },
        FLAG: {
          type: 'string',
          title: '派件状态',
          default: rec.STATUS,
          enum: this.supdic.getSFDic('AAE100'),
          ui: {
            widget: 'select',
            allowClear: true,
            grid: { span: 6 }
          }
        },
      },
      required: ['CZE028', 'CZE029', 'CZE030', 'CZE031'],
    };
    this.chVisible = true;
  }
  fwuphandleCancel() {
    this.chVisible = false;
  }

  fwuphandleOk() {
    this.lbservice
      .lbservice('FR_userupdate', { para: this.changePop.value })
      .then(resdata => {
        if (resdata.code > 0) {
          this.msgSrv.success('更改成功');
        } else {
          this.msgSrv.error(resdata.errmsg);
        }
        this.st.reload();
        this.chVisible = false;
      });
  }
}
